import React, { Component } from 'react';
import moment from 'moment';
import { LineChart } from '#/components/Charts/';
import { ApiOfTpsEndpoint } from '#/utils/metricApiDefine'

export default class TpsSplineChart extends Component {
  static displayName = 'TpsSplineChart';
  constructor(props) {
    super(props);
    this.state = {
      endpoints: []
    };
    this.timeoutId = -1;
  }

  componentWillMount() {
    this.fetch();
  }

  render() {
    return (
      <LineChart 
        data= {this.state.endpoints} 
        xAxisVisible={true} 
        legendVisible={false} 
        height={240}/>
    );
  }

  componentWillUnmount() {
    clearTimeout(this.timeoutId)
    this.setState({
      endpoints: []
    })
  }

  fetch = () => {
    let that = this;
    ApiOfTpsEndpoint().then(response => {
      if(!!response.time) {

        const data = {time: response.time,xAxis: moment(response.time).format('HH:mm:ss'), yAxis: response.tps, field: 'tps'}
        let endpoints = [...this.state.endpoints, data]
        endpoints = endpoints.slice(endpoints.length > 20 ? endpoints.length-20: 0 ,endpoints.length)
        this.setState({
          endpoints
        })
      }

      that.timeoutId = setTimeout(()=>{
        that.fetch();
      }, 3000)
    })
  }
}